package com.panda.multiple.tenant.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.panda.multiple.tenant.config.MyTableNameHandler;
import com.panda.multiple.tenant.dao.UserMapper;
import com.panda.multiple.tenant.domain.po.User;
import com.panda.multiple.tenant.domain.vo.UserVO;
import com.panda.multiple.tenant.service.TenantService;
import com.panda.multiple.tenant.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private final ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();


    @Resource
    private UserMapper userMapper;

    @Resource
    private TenantService tenantService;

    @Override
    public UserVO getUserById(Long id) {
        MyTableNameHandler.setTableNameSuffix(tenantService.getTenantInfoForLoginUser());
        User user = getBaseMapper().selectById(id);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return userVO;
    }

    @Override
    public Integer updateById(UserVO userVO) {
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        return getBaseMapper().updateById(user);
    }

    @Override
    public Boolean addUser(UserVO userVO) {
        writeLock.lock();
        try {
            // 查询用户表是否已经存在用户信息
            // 如果主键是分布式全局ID则根据ID查询，或者根据身份证号，手机号等唯一索引字段查询
            User existUser = getBaseMapper().selectUserById(userVO.getId());
            if (Objects.isNull(existUser)) {
                User user = new User();
                BeanUtils.copyProperties(userVO, user);
                getBaseMapper().insert(user);
            } else {
                log.warn("重复请求： {}", JSON.toJSONString(userVO));
                return true;
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        } finally {
            writeLock.unlock();
        }
        return true;
    }

}
